{{ template "header_" . }}

<h1>Connection: <tt>{{ .Name }}</tt></h1>

{{ if .Caps.SupportsConnectionInit }}
<button onclick='location.href="/connections/{{ .ID }}/init/dash"'>Initialize
    {{ if .Caps.RequiresConnectionInit }}(required){{ end }}</button>
{{ end }}

{{ if .Caps.SupportsConnectionTest }}
<button onclick='testConnection()'>Test</button> <input type="text" id="test-result" readonly hidden>
{{ end }}


<pre>{{ .JSON }}</pre>

{{ template "vars_" .Vars }}

<h2>{{ .Events.N }} Events</h2>
{{ template "list_table_" .Events}}

<script>
    function testConnection() {
        fetch("/connections/{{ .ID }}/test", {
            method: "POST",
        }).then(async response => {
            if (response.ok) {
                const data = await response.json()
                console.log(data)
                const el = document.getElementById("test-result")

                let text = data['code'] || ''
                if (data['message']) {
                    if (text) {
                        text += ": "
                    }
                    text += data['message']
                }

                el.value = text
                el.hidden = false
            } else {
                console.error(response)
                alert("Failed to test connection")
            }
        }).catch(error => {
            console.error(error)
            alert("Failed to test connection")
        })
    }
</script>

{{ template "footer_" . }}
